package com.jilintongyi.jlcrtvu.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.jilintongyi.jlcrtvu.entity.SysLog;
import com.jilintongyi.jlcrtvu.service.LogService;
import com.jilintongyi.jlcrtvu.service.UserService;
import com.jilintongyi.jlcrtvu.util.HttpUtils;

/**
 * 登录成功处理
 */
@Component
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
	@Autowired
	LogService logService;

	@Autowired
	UserService userService;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws ServletException, IOException {
		SysLog log = new SysLog();
		log.setUser(userService.findByUsername(authentication.getName()));
		log.setContent("登录成功");
		log.setIp(HttpUtils.getIpAddress(request));
		logService.save(log);

		// username放到session中供Druid使用
		request.getSession().setAttribute("username", authentication.getName());

		// 成功跳转
		setDefaultTargetUrl("/admin/index");
		// 总是使用设置的跳转，不跳回来源页
		setAlwaysUseDefaultTargetUrl(true);
		super.onAuthenticationSuccess(request, response, authentication);
	}
}
